import React, { useState, useEffect, useRef } from 'react';
import { Drawer, Input, Loading, notification } from '@ss/mtd-react';
import { Button, Form, Select, AsyncButton, Tag } from '@block/plug';
import M from '@block/utils';
import { RuleDetail } from '../../type';
import URL from '../../url';
import './RuleDetailDrawer.scss';

/** Props 声明 */
interface Props {
  /** 规则id */
  ruleId: number;
  /** 侧滑状态标志 */
  drawerMode: PageMode;
  /**  关闭弹窗方法 */
  setDetailDrawerVisible: React.Dispatch<React.SetStateAction<boolean>>;
  /** 搜索列表刷新方法 */
  recordsSearch: () => void;
  /** 更新tab角标数据方法 */
  getStatusCount: () => void;
  /** setQueryString 方法 */
  setSearchParams?: any;
}

/**
 * 规则详情侧滑
 */
const RuleDetailDrawer = (props: Props) => {
  const { ruleId, drawerMode, setDetailDrawerVisible, recordsSearch, getStatusCount, setSearchParams } = props;

  /** state状态声明 */
  const [loading, setLoading] = useState<boolean>(false); // 页面loading状态
  const [jobFamilyId, setJobFamilyId] = useState<string>(); // jobFamilyId参数存储

  /** ref 声明 */
  const ruleDetailFormRef = useRef<Form>(null);

  /** 获取侧滑详情数据 */
  const ruleDetailInitData = async () => {
    if (drawerMode !== 'create') {
      setLoading(true);
      try {
        const res = await M.$fetch<RuleDetail>(URL.viewRule, { ruleId });
        if (res.subordinateInfo === true) {
          res.subordinateInfo = { code: 1, name: '是' };
        } else if (res.subordinateInfo === false) {
          res.subordinateInfo = { code: 0, name: '否' };
        }
        setJobFamilyId(res?.jobFamilyId?.code);
        ruleDetailFormRef.current?.setFieldsValue(res);
      } finally {
        setLoading(false);
      }
    }
  };

  /** didMount */
  useEffect(() => {
    ruleDetailInitData();
  }, []);

  /**
   * 编辑态的修改保存处理
   * @param e event
   * @param btn 按钮实例
   */
  const handleSave = async (e: MouseEvent, btn: Button) => {
    if (ruleDetailFormRef.current?.validateFields()) {
      const params = ruleDetailFormRef.current?.getFieldsValue();
      params.jobGroupIdList = params.jobGroupIdList?.map((item) => item?.code);
      params.levelList = params.levelList?.map((item) => item?.code);
      params.sensitivePosTypeList = params.sensitivePosTypeList.map((item) => item.code);

      try {
        btn.loading(true);
        let res = null;
        if (drawerMode === 'create') {
          res = await M.$fetch<OperateResponse>(URL.addRule, params);
        }
        if (drawerMode === 'edit') {
          params.ruleId = ruleId;
          res = await M.$fetch<OperateResponse>(URL.modifyRule, params);
        }
        notification.success({ title: '成功', message: res?.message || '操作成功' });
        setDetailDrawerVisible(false);
        recordsSearch();
        setSearchParams?.('');
        getStatusCount();
      } finally {
        btn.loading(false);
      }
    }
  };

  return (
    <div style={{ height: '600px' }}>
      <Drawer
        title={
          <div className="rule-detail-drawer-title">
            <div className="header-title">规则详情</div>
            {drawerMode !== 'view' && (
              <div className="header-btns">
                <Button
                  onClick={() => {
                    setSearchParams?.('');
                    setDetailDrawerVisible(false);
                  }}
                >
                  取消
                </Button>
                <AsyncButton type="primary" onClick={handleSave}>
                  保存
                </AsyncButton>
              </div>
            )}
          </div>
        }
        width={600}
        visible
        onClose={() => {
          setSearchParams?.('');
          setDetailDrawerVisible(false);
        }}
      >
        <Loading loading={loading}>
          <Form
            ref={ruleDetailFormRef}
            labelWidth="120px"
            labelPosition="right"
            labelInValue={false}
            mode={drawerMode}
            onFieldValueChange={(key: string, value) => {
              if (key === 'jobFamilyId') {
                setJobFamilyId(value);
                ruleDetailFormRef.current?.setFieldsValue({ jobGroupIdList: null });
              }
            }}
          >
            {['view', 'edit'].includes(drawerMode) && (
              <>
                <Form.Item formItemKey="ruleStatusName" label="状态：" span={24}>
                  {(e) => <Tag>{e.parentForm.getFieldsValueIncludeHide().ruleStatusName}</Tag>}
                </Form.Item>
                <Form.Item formItemKey="createTime" label="创建时间：" span={24}>
                  {(e) => <span>{M.datejs(e.value).format('YYYY-MM-DD HH:mm:ss')}</span>}
                </Form.Item>
                <Form.Item formItemKey="validTime" label="生效时间：" span={24}>
                  {(e) => <span>{M.datejs(e.value).format('YYYY-MM-DD HH:mm:ss')}</span>}
                </Form.Item>
                <Form.Item formItemKey="creatorEmpName" label="创建人：" span={24}>
                  {(e) => <span>{e.value}</span>}
                </Form.Item>
                <Form.Item formItemKey="ruleNumber" label="规则编号：" span={24}>
                  {(e) => <span>{e.value}</span>}
                </Form.Item>
                <Form.Item formItemKey="version" label="规则版本：" span={24}>
                  {(e) => <span>{e.value}</span>}
                </Form.Item>
                <Form.Item formItemKey="personListCount" label="名单：" span={24}>
                  {(e) => <span>{e.value}</span>}
                </Form.Item>
              </>
            )}
            <Form.Item formItemKey="orgId" label="适用组织：" required message="请填写必填项" span={24}>
              <Select
                keyField="code"
                labelField="name"
                placeholder="请输入适用组织"
                dispatchFetchDataWithoutKeyword={false}
                toFormItem
                onFetchData={(search: string) =>
                  M.$fetch<SelectOption<string>[]>(URL.queryOrgList, { search: search?.trim() })
                }
              />
            </Form.Item>
            <Form.Item formItemKey="jobFamilyId" label="JobFamily：" span={24}>
              <Select
                keyField="code"
                labelField="name"
                filterable={false}
                placeholder="请选择JobFamily"
                toFormItem
                onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.queryJobFamily)}
              />
            </Form.Item>
            <Form.Item formItemKey="jobGroupIdList" label="JobGroup：" span={24}>
              <Select
                keyField="code"
                labelField="name"
                disabled={!jobFamilyId}
                multiple
                filterable={false}
                placeholder="请选择JobGroup"
                toFormItem
                onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.queryJobGroupByJobFamilyId, { jobFamilyId })}
              />
            </Form.Item>
            <Form.Item formItemKey="levelList" label="职级：" span={24}>
              <Select
                keyField="code"
                labelField="name"
                multiple
                onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.queryLevelList)}
                placeholder="请选择职级"
                toFormItem
              />
            </Form.Item>
            <Form.Item formItemKey="subordinateInfo" label="是否有下属：" span={24}>
              <Select
                keyField="code"
                labelField="name"
                filterable={false}
                onFetchData={() => {
                  return [
                    { code: 1, name: '是' },
                    { code: 0, name: '否' },
                  ];
                }}
                placeholder="请选择敏感岗位分类"
                toFormItem
              />
            </Form.Item>
            <Form.Item
              formItemKey="sensitivePosTypeList"
              required
              message="请填写必填项"
              label="敏感岗位分类："
              span={24}
            >
              <Select
                keyField="code"
                labelField="name"
                multiple
                filterable={false}
                onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.querySensitivePosTypeList)}
                placeholder="请选择敏感岗位分类"
                toFormItem
              />
            </Form.Item>
            <Form.Item formItemKey="riskDesc" label="风险描述：" span={24}>
              <Input.TextArea
                showCount
                placeholder="请输入纳入敏感岗位管理原因，如该岗位风险等"
                toFormItem
                maxLength={500}
              />
            </Form.Item>
          </Form>
        </Loading>
      </Drawer>
    </div>
  );
};

export default RuleDetailDrawer;
